package com.xiaoshangkou.hellopra.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshangkou.hellopra.bean.Permission2WithStatus;
import com.xiaoshangkou.hellopra.bean.PermissionWithStatus;
import com.xiaoshangkou.hellopra.mapper.Permission2Mapper;
import com.xiaoshangkou.hellopra.mapper.UserGroupMapper;
import com.xiaoshangkou.hellopra.pojo.Permission;
import com.xiaoshangkou.hellopra.pojo.Permission2;
import com.xiaoshangkou.hellopra.pojo.UserGroup;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 关于数据库中的用户组服务层
 *
 */
@Service
public class UserGroupService {
    @Autowired
    private UserGroupMapper userGroupMapper;

    @Autowired
    private Permission2Mapper permission2Mapper;

    //分页查询用户组
    public Page<UserGroup> findPage(int page,int size){
        Page<UserGroup> userGroupPage = userGroupMapper.selectPage(new Page<>(page, size), null);
        return userGroupPage;
    }

    //新增用户组
    public void add(UserGroup userGroup){
        userGroupMapper.insert(userGroup);
    }

    //删除用户组
    public void delete(Integer uid){
        userGroupMapper.deleteById(uid);
    }

    //根据uid获取用户组内容
    public UserGroup findById(Integer uid){
        return userGroupMapper.selectById(uid);
    }

    //更新用户组内容
    public void update(UserGroup userGroup){
        userGroupMapper.updateById(userGroup);
    }

    //查找所有权限，以及角色拥有的权限
    public List<Permission2WithStatus> findPermission(Integer uid){
        List<Permission2> permission2 = permission2Mapper.selectList(null);//查询所有权限
        List<Integer> permissionIdByRole = permission2Mapper.findPermission2IdByUserGroup(uid);//查询用户组拥有的权限id
        List<Permission2WithStatus> permissionWithStatuses=new ArrayList<>();//创建带有状态的权限集合
        for (Permission2 permission : permission2) {
            Permission2WithStatus permission2WithStatus=new Permission2WithStatus();
            //将普通权限类复制给带有状态的权限类
            BeanUtils.copyProperties(permission,permission2WithStatus);
            if (permissionIdByRole.contains(permission.getPeid2())){//当权限循环到用户组拥有的权限时
                permission2WithStatus.setPermissionHas(true);
            }else {
                permission2WithStatus.setPermissionHas(false);
            }
            permissionWithStatuses.add(permission2WithStatus);
        }

        return permissionWithStatuses;
    }

    //给角色重新赋予权限
    public void updatePermissioon2(Integer[] ids,Integer uid){
        //先删除所有权限再重新赋予用户选中的权限
        userGroupMapper.deleteUserGroupAllPermission2(uid);//删除所有权限
        //赋予权限
        for (Integer peid2 : ids) {
            userGroupMapper.addUserGroupermission2(uid,peid2);
        }
    }

}
